package com.solarfridge.monitor.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.solarfridge.monitor.shared.LoginInfo;
import com.solarfridge.monitor.shared.data.Fridge;

public class AdminPage implements EntryPoint {

	private static String MAIN_CONTAINER = "mainContainer";
		
	private final DataServiceAsync dataService = 
		DataService.Util.getInstance();

	@Override
	public void onModuleLoad() {
		//http://code.google.com/webtoolkit/doc/latest/tutorial/appengine.html

		// Check login status using login service.
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		String requestUri = GWT.getModuleBaseURL();
		requestUri = requestUri.substring(0, requestUri.length() - 1);
		requestUri = requestUri + ".html";
		loginService.login(requestUri, new AsyncCallback<LoginInfo>() {
			public void onFailure(Throwable error) {
				Label errorText = new Label("An error has occured logging in. Please try again.");
				RootPanel.get(MAIN_CONTAINER).add(errorText);
			}

			public void onSuccess(LoginInfo result) {
				if(result.isLoggedIn()) {
					loadAdminPage(result);
				} else {
					loadLogin(result);
				}
			}
		});
	}

	private void loadAdminPage(LoginInfo loginInfo){
		final AdminPageBinder binder = new AdminPageBinder(loginInfo);
		RootPanel.get().add(binder);
						
		
		dataService.getFridgeList(new AsyncCallback<Fridge[]>() {			
			@Override
			public void onSuccess(Fridge[] result) {
				binder.populateFridgeList(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}
		});
		
	}

	private void loadLogin(LoginInfo loginInfo){
		VerticalPanel loginPanel = new VerticalPanel();
		Label loginLabel = new Label("Please sign in with an authorized Google Account to access the Solar Fridge Monitor.");
		Anchor signInLink = new Anchor("Sign In");
		signInLink.setHref(loginInfo.getLoginUrl());
		
		Anchor returnLink = new Anchor("Home", "/");
		loginPanel.add(loginLabel);
		loginPanel.add(signInLink);
		loginPanel.add(returnLink);
		RootPanel.get(MAIN_CONTAINER).add(loginPanel);
	}

}
